package com.scanner.net;

import com.scanner.util.DataUtil;
import com.scanner.util.LogUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import io.reactivex.observers.DefaultObserver;
import okhttp3.ResponseBody;

public class RxFileDownLoadObserver<T> extends DefaultObserver<T> {

    private RxProgressListener listener;

    public RxFileDownLoadObserver(RxProgressListener listener){
        this.listener = listener;
    }

    @Override
    public void onNext(T t) {
        listener.onFinishDownload((File) t);
    }

    @Override
    public void onError(Throwable e) {
        listener.onFail(e.getMessage());
    }

    @Override
    public void onComplete() {

    }

    /**
     * 将文件写入本地
     * @param responseBody 请求结果全体
     * @param destFileDir 目标文件夹
     * @param destFileName 目标文件名
     * @return 写入完成的文件
     * @throws IOException IO异常
     */
    public File saveFile(ResponseBody responseBody, String destFileDir, String destFileName) throws IOException {
        LogUtil.d("开始流下载时间=="+ DataUtil.getCurrentDateStringTw());
        InputStream is = null;
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream fos = null;
        try {
            is = responseBody.byteStream();
            final long total = responseBody.contentLength();
            long sum = 0;

            File dir = new File(destFileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, destFileName);
            fos = new FileOutputStream(file);
            LogUtil.d("开始流下载时间2222=="+ DataUtil.getCurrentDateStringTw());
            while ((len = is.read(buf)) != -1) {
                sum += len;
                fos.write(buf, 0, len);
                final long finalSum = sum;
            }
            fos.flush();

            return file;

        } finally {
            try {
                if (is != null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
                listener.onFail(e.getMessage());
            }
            try {
                if (fos != null) fos.close();
            } catch (IOException e) {
                e.printStackTrace();
                listener.onFail(e.getMessage());
            }
        }
    }


}
